package cn.ylz.ylmall.content.service.impl;

import cn.ylz.ylmall.account.security.CurrentPrincipal;
import cn.ylz.ylmall.common.web.JsonResult;
import cn.ylz.ylmall.content.dao.persist.repository.ICollectRepository;
import cn.ylz.ylmall.content.pojo.entity.Collect;
import cn.ylz.ylmall.content.pojo.param.CollectAddNewParam;
import cn.ylz.ylmall.content.pojo.vo.CollectStandardVO;
import cn.ylz.ylmall.content.pojo.vo.CountVO;
import cn.ylz.ylmall.content.service.ICollectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

import static cn.ylz.ylmall.common.web.ServiceCode.COLLECT_CANCEL;
import static cn.ylz.ylmall.common.web.ServiceCode.COLLECT_SUCCESS;

@Slf4j
@Service
public class CollectServiceImpl implements ICollectService {
    @Autowired
    private ICollectRepository collectRepository;
    @Override
    public JsonResult addNew(CurrentPrincipal currentPrincipal, CollectAddNewParam collectAddNewParam) {
        log.debug("开始处理【添加收藏】的请求，参数：{}", collectAddNewParam);
        Collect collect = new Collect();
        BeanUtils.copyProperties(collectAddNewParam, collect);
        collect.setUserId(currentPrincipal.getId());
        collect.setCollectTime(new Date());
        log.debug("收藏信息为:{}", collect);
        //检测是否已经收藏
        CollectStandardVO result = collectRepository.selectIsCollect(currentPrincipal.getId(),collectAddNewParam.getContentId());
        if(result == null){
            int rows = collectRepository.insert(collect);
            if(rows != 1) {
                throw new RuntimeException("添加收藏失败");
            }
            return JsonResult.ok(COLLECT_SUCCESS);
        }else {
            int rows = collectRepository.delete(currentPrincipal.getId(),collectAddNewParam.getContentId());
            if(rows != 1) {
                throw new RuntimeException("取消收藏失败");
            }
        }
            return JsonResult.ok(COLLECT_CANCEL);
    }

    @Override
    public CountVO count(Long contentId) {
        log.debug("开始处理【根据内容ID统计收藏数量】的请求，参数：{}", contentId);
        return collectRepository.count(contentId);
    }

    @Override
    public Boolean selectIsCollect(Long id, Long contentId) {
        CollectStandardVO result = collectRepository.selectIsCollect(id,contentId);
        if(result == null){
            return false;
        }
        return true;
    }
}
